package com.example.smartall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.smartall.R;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.entity.LoginBean;
import com.example.smartall.entity.UserInfoBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.example.smartall.utils.SPUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener{
    private EditText etName;
    private EditText etPassword;
    private Button btRegister;
    private Button btLogin;
    private SPUtils spUtils;
    private LoadedDialog dialog;
    private MHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        spUtils = SPUtils.config(this,Constant.SP_USER_FILE_NAME);
        handler = new MHandler();
        init();
        initEvent();
    }

    public void init() {
        etName = (EditText) findViewById(R.id.et_name);
        etPassword = (EditText) findViewById(R.id.et_password);
        btRegister = (Button) findViewById(R.id.bt_register);
        btLogin = (Button) findViewById(R.id.bt_login);
    }

    public void initEvent() {
        btLogin.setOnClickListener(this);
        btRegister.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dialog = new LoadedDialog(getThis());
    }

    private void Login(){
        dialog.show();

        String userName = etName.getText().toString();
        String password = etPassword.getText().toString();
        HashMap<String,Object> params = new HashMap<>();
        params.put(Constant.USERNAME,userName);
        params.put(Constant.PASSWORD,password);
        Api.config(ApiConfig.LOGIN_URL,params).postRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                LoginBean loginBean = new Gson().fromJson(res,LoginBean.class);
                if (200 == loginBean.getCode()){
                    spUtils.putString(Constant.USER_NAME,userName);
                    spUtils.putString(Constant.PASSWORD,password);
                    spUtils.putString(Constant.TOKEN,loginBean.getToken());
                    Message message = handler.obtainMessage();
                    message.what = 0x01;
                    message.obj = loginBean.getToken();
                    handler.sendMessage(message);
                }
                showToastSync(loginBean.getMsg());
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        },"");
    }

    public void getUserInfo(String token){
        dialog.show();
        Api.config(ApiConfig.USERINFO_URL,null).getRequest(getThis(), new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                UserInfoBean userInfoBean = new Gson().fromJson(res,UserInfoBean.class);
                if (userInfoBean.getCode() == 200){
                    spUtils.putString(Constant.USER_NICKNAME,userInfoBean.getUser().getNickName());
                    spUtils.putString(Constant.USER_ID,userInfoBean.getUser().getUserId()+"");
                    spUtils.putString(Constant.USER_EMAIL,userInfoBean.getUser().getEmail()+"");
                    spUtils.putString(Constant.USER_PHONENUMBER,userInfoBean.getUser().getPhonenumber()+"");
                    spUtils.putString(Constant.USER_SEX,userInfoBean.getUser().getSex()+"");
                    spUtils.putString(Constant.USER_AVATAR,userInfoBean.getUser().getAvatar()+"");
                    spUtils.putString(Constant.USER_ID_CARD,userInfoBean.getUser().getIdCard()+"");
                    spUtils.putString(Constant.USER_BALANCE,userInfoBean.getUser().getBalance()+"");
                    spUtils.putString(Constant.USER_SCORE,userInfoBean.getUser().getScore()+"");
                    handler.sendEmptyMessage(0x02);
                }else {
                    showToastSync(userInfoBean.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        },"");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_login:
                Login();
                break;
            case R.id.bt_register:
                migrateTo(RegisterActivity.class);
                break;
        }
    }
    class MHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x01:
                    getUserInfo((String) msg.obj);
                    break;
                case 0x02:
                    LoginActivity.this.finish();
                    break;
                default:
                    break;
            }
        }
    }
}